<template>
  <div class="container" v-loading="loading">
    <el-steps style="margin-top: -20px;" :active="active" simple finish-status="finish" process-status="finish">
      <el-step v-for="(item, index) in stepOptions" :key="item.title" :title="item.title">
        <div class="fs-sm" slot="icon">{{ index + 1 }}</div>
      </el-step>
    </el-steps>

    <div class="content">
      <div v-if="active === 0" class="select">
        <div class="pd10 fs-sm text-gray">设置时间点后，每日将帮您自动刷新端口上的上架房源哦～</div>
        <div :class="[index === 0 ? '' : 'mt30']" v-for="(item, index) in selectList" :key="item.title">
          <RefreshSelect :row="item" @setting="handleSetting" @toggle="handleToggle"></RefreshSelect>
        </div>
      </div>
      <div v-if="active === 1" class="setting">
        <RefreshTime :currentSetting="currentSetting" @back="handleBack" @close="handleClose"></RefreshTime>
      </div>
      <div v-if="active === 2" class="finish"></div>
    </div>
  </div>
</template>

<script>
import RefreshTime from './RefreshTime';
import RefreshSelect from './RefreshSelect';
import { checkPermission, checkPermissionByStatus } from '@/handler/permission';
export default {
  name: 'RefreshSetting',

  components: {
    RefreshTime,
    RefreshSelect
  },

  inject: {
    rootPort: {
      default() {
        return {};
      }
    }
  },

  props: {},

  data() {
    this.houseTypeMap = {
      SALES: '二手房',
      RENT: '租房'
    };
    this.stepOptions = [{ title: '选择类型' }, { title: '设置时间点' }, { title: '设置完成' }];
    return {
      loading: false,
      active: 0,
      currentSetting: {
        type: '',
        id: ''
      },
      selectList: [
        {
          id: '',
          houseType: 'SALES',
          title: '二手房',
          houseAddedStatus: '上架房源',
          timePointsNum: 0,
          taskStatus: '0',
          stopType: '',
          stopReason: '',
          isLoading: false
        },
        {
          id: '',
          houseType: 'RENT',
          title: '租房',
          houseAddedStatus: '上架房源',
          timePointsNum: 0,
          taskStatus: '0',
          stopType: '',
          stopReason: '',
          isLoading: false
        }
      ]
    };
  },

  computed: {},

  watch: {},

  beforeMount() {},

  mounted() {
    this.loadHouseRefreshData();
  },

  methods: {
    // ------------------handle------------------
    async handleSetting(e) {
      if (await checkPermission()) {
        this.currentSetting.type = e.type || '';
        this.currentSetting.id = e.id || '';
        this.next();
      }
    },
    handleBack() {
      this.prev();
      this.loadHouseRefreshData();
    },
    handleClose() {
      this.$emit('close');
    },
    handleToggle(e) {
      this.toggleRefreshStatus(e.status, e.id);
    },
    // ------------------function------------------
    // 加载房源刷新数据
    async loadHouseRefreshData() {
      try {
        this.loading = true;
        let res = await this.$api.getRefreshSelectList({
          userPortId: this.rootPort.portInfo.id || ''
        });
        if (res && res.content && res.content.length) {
          const map = {};
          res.content.forEach((item) => {
            let { delegationType, id, status, stopType, stopReason } = item.hmAutoRefreshInfo;
            map[delegationType] = {
              id: id || '',
              houseType: delegationType || '',
              title: this.houseTypeMap[delegationType] || '',
              houseAddedStatus: '上架房源',
              timePointsNum: item.count || 0,
              taskStatus: status || '',
              stopType: stopType || '',
              stopReason: stopReason || ''
            };
          });
          this.selectList.forEach((item) => {
            if (map[item.houseType]) {
              Object.assign(item, map[item.houseType]);
            }
          });
        }
      } catch (error) {
        console.log('error', error);
      } finally {
        this.loading = false;
      }
    },
    // 切换自动刷新开关
    async toggleRefreshStatus(status, id) {
      try {
        if (!id || !status) {
          return;
        }
        this.selectList.forEach((item) => {
          if (item.id === id) {
            item.isLoading = true;
          }
        });
        let res = await this.$api.changeAutoRefreshStatus({
          id,
          status
        });
        if (['SET_ENABLE_SUCCESS', 'SET_DISABLE_SUCCESS'].indexOf(res.content.resultCode) !== -1) {
          this.loadHouseRefreshData();
          this.$message.success(res.content.resultMessage);
          return;
        }
        if (['VIP_ERROR'].indexOf(res.content.resultCode) !== -1) {
          checkPermissionByStatus(res.content.resultMessage);
          return;
        }
        if (['PORT_ERROR'].indexOf(res.content.resultCode) !== -1) {
          this.$alert(res.content.resultMessage, '提示', {
            confirmButtonText: '确定',
            callback: (action) => {}
          });
          return;
        }
        this.$message.success('操作失败, 请稍后再试~');
      } catch (error) {
        console.log('error', error);
      } finally {
        this.selectList.forEach((item) => {
          if (item.id === id) {
            item.isLoading = false;
          }
        });
        this.isShowPage = true;
      }
    },
    next() {
      if (this.active >= this.stepOptions.length - 1) return;
      this.active++;
    },
    prev() {
      if (this.active <= 0) return;
      this.active--;
    }
  }
};
</script>
<style lang="scss" scoped>
.container {
  height: 480px;
}
</style>
